<template>
  <div id="firmware-update">
    <Row type='flex'
         justify="space-between"
         style="padding:20px">
      <Row type='flex'>
        <Col>
        <RadioGroup v-model="buttonValue"
                    type="button"
                    @on-change='changeBtn'>
          <Radio label="0">固件列表</Radio>
          <Radio label="1">门店列表</Radio>
        </RadioGroup>
        </Col>
        <Col v-show="buttonValue === '1'">
        <Row type='flex'
             align='middle'>
          <Col>
          <span style="margin: 0 8px 0 48px">门店名称：</span>
          </Col>
          <Col>
          <Select v-model="inputValue"
                  filterable
                  :clearable='true'
                  @on-change='changeStore'>
            <Option v-for="item in storeList"
                    :value="item.shopName"
                    :key="item.shopId">{{ item.shopName }}</Option>
          </Select>
          </Col>
        </Row>
        </Col>
      </Row>
      <Col>
      <Upload ref="upload"
              :action="$config.uploadUrl"
              :on-format-error="handleFormatError"
              :on-success="handleSuccess"
              :on-error='handleErr'
              type="select"
              :format="['apk', 'hex', 'zip']"
              :data='loadData'>
        <Button type="primary">上传物料</Button>
      </Upload>
      </Col>
    </Row>
    <Row>
      <Col v-show="buttonValue === '0'">
      <Table stripe
             :columns="columnsData1"
             :data="materialList"
             :loading='loading1'
             :height="this.tableHeight"
             class="table-list">
        <template slot-scope="{ row }"
                  slot="action">
          <i class="iconsys iconsetting"
             title="批量设置"
             @click='allSet(row)'></i>
          <i class="iconsys icondel"
             title="删除"
             @click='delPageShow(row)'></i>
        </template>
      </Table>
      <Modal title="确认提示"
             width='400'
             v-model="delReason">
        <Row type='flex'
             justify="space-between"
             align='middle'
             style="margin-bottom:20px;">
          <Col style="padding-left:10px;">
          <Icon type="ios-alert"
                size="30"
                color="#ffbf00" />
          <span style="margin-left:10px;font-weight:bold;color:#666666;">是否确认删除?</span>
          <Poptip word-wrap
                  width="200"
                  content="删除后,将解绑与门店的关系">
            <Icon type="ios-alert-outline"
                  size="18"
                  style='margin-left:5px' />
          </Poptip>
          </Col>
        </Row>
        <Form :model="delValidate"
              ref="delValidate"
              :label-width="50"
              :rules="delRule">
          <FormItem label="原因:"
                    prop="remark">
            <Input v-model="delValidate.remark"
                   style="width:280px;"
                   type="textarea"
                   :maxlength="100"
                   :autosize="{minRows: 2,maxRows: 5}"
                   placeholder="输入删除原因" />
                   <p style="text-align:right;width:280px">已输入{{delValidate.remark?delValidate.remark.length:0}}/100</p>
          </FormItem>
        </Form>
        <div slot="footer"
             class="foot">
          <Button class="btn"
                  @click='cancelDel'>取消</Button>
          <Button type="primary"
                  class="btn"
                  style="margin-right:16px;"
                  @click="delMaterial">确认</Button>
        </div>
      </Modal>
      </Col>
      <Col v-show="buttonValue === '1'">
      <Table stripe
             :columns="columnsData2"
             :data="shopList"
             :loading='loading2'
             class="table-list"
             :height="this.tableHeight">
        <template slot-scope="{ row }"
                  slot="action">
          <i class="iconsys icondetail"
             title="查看历史记录"
             @click="openDraw(row)"></i>
        </template>
      </Table>
      </Col>
      <Col>
      <Row type='flex'
           justify="end"
           class='page-bottom'>
        <Col>
        <Page :total="buttonValue === '0'? total: storeTotal"
              :current="buttonValue === '0'? pageIndex: storePageIndex"
              :page-size="buttonValue === '0'? pageSize: storePageSize"
              show-sizer
              show-total
              @on-change='changePage'
              @on-page-size-change='changePageSize' />
        </Col>
      </Row>
      </Col>
    </Row>
    <select-shop :checkdList="checkdList"
                 :dataTree="dataTree"
                 :modalShow="modalShow"
                 @oncancel="selctshopCancle"
                 @selctshop="volumeSet"
                 v-if="modalShow">
    </select-shop>
    <Drawer title="历史记录"
            :closable="true"
            :transfer='false'
            v-model="historyShow"
            width="55%">
      <Table stripe
             :columns="columnsData3"
             :data="historyList"
             class="table-list"
             :height="this.tableHeight">
        <template slot-scope="{ row }"
                  slot="type">
          <span>{{row.materialType === 0 ? '固件包': '待机动画'}}</span>
        </template>
        <template slot-scope="{ row }"
                  slot="itemName">
          <span>{{row.materialName.split('_')[0]}}</span>
        </template>
        <template slot-scope="{ row }"
                  slot="version">
          <span>{{row.materialName.split('_')[1].split('.')[0]}}</span>
        </template>
      </Table>
      <div class="demo-drawer-footer">
        <Row type='flex'
             justify="end"
             class="page-bottom">
          <Col>
          <Page :total="historyTotal"
                :page-size='historyPageSize'
                show-sizer
                show-total
                @on-change='changeHistoryPage'
                @on-page-size-change='changeHistoryPageSize' />
          </Col>
        </Row>
      </div>
    </Drawer>
  </div>
</template>

<script>
import SelectShop from '@/view/components/select-shop/select-shop.vue'
import { getShopList } from '@/api/system/store'
import { getOrgAllTree } from '@/api/system/org'
import { getMaterialList, shopMaterialList, getHistoryList, delectMaterial, saveWholeMaterialInfos, saveMaterialInfos } from '@/api/setting'
export default {
  components: {
    SelectShop
  },
  data () {
    return {
      tableHeight: 0,
      loading1: true,
      loading2: true,
      isDelete: true,
      loadData: {
        project: 'material',
        type: 'firmware'
      },
      delReason: false, // 删除原因状态
      delValidate: {
        remark: ''
      },
      delRule: {
        remark: { required: true, message: '删除原因不能为空', trigger: 'blur' }
      },
      materialId: '',
      storeTotal: 0,
      storePageIndex: 1,
      storePageSize: 10,
      historyTotal: 0,
      historyPageIndex: 1,
      historyPageSize: 10,
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      inputValue: '',
      shopId: '',
      storeList: [],
      historyShow: false, // 历史记录
      buttonValue: '0', // 0固件列表 1门店列表
      modalShow: false, // 批量操作对话框显示
      dataTree: [], // 树
      checkdList: [], // 已选的数组
      columnsData1: [
        {
          title: '物料名称',
          key: 'materialName',
          align: 'center'
        },
        {
          title: '上传时间',
          key: 'createTime',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center'
        }
      ],
      columnsData2: [
        {
          title: '门店名称',
          key: 'shopName',
          align: 'center'
        },
        {
          title: '物料名称',
          key: 'materialName',
          align: 'center'
        },
        {
          title: '上传时间',
          key: 'createTime',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center'
        }
      ],
      columnsData3: [
        {
          title: '发布时间',
          key: 'createTime',
          align: 'center'
        },
        {
          title: '物料名称',
          key: 'materialName',
          align: 'center'
        },
        {
          title: '固件类型',
          slot: 'type',
          align: 'center'
        },
        {
          title: '项目名称',
          slot: 'itemName',
          align: 'center'
        },
        {
          title: '固件版本号',
          slot: 'version',
          align: 'center'
        }
      ],
      // 固件列表数据
      materialList: [],
      // 门店列表数据
      shopList: [],
      // 历史记录数据
      historyList: []
    }
  },
  watch: {
    modalShow (val) {
      if (!val) {
        this.dataTree = []
        this.checkdList = []
      }
    },
    delReason (val) {
      if (!val) {
        this.$refs.delValidate.resetFields()
      }
    }
  },
  methods: {
    selctshopCancle () {
      this.modalShow = false
    },
    changeTitle (arr) {
      arr.forEach(item => {
        this.$set(item, 'title', item.orgName)
        this.$set(item, 'checked', false)
        if (item.hasOwnProperty('childList') && item.childList.length > 0) {
          this.changeTitle(item.childList)
        }
      })
    },
    volumeSet (val) {
      if (val.length > 0) {
        this.shopIdList = []
        val.forEach(ele => {
          this.shopIdList.push(ele.id)
        })
        saveMaterialInfos({
          materialType: 0,
          merchantId: this.$store.state.user.merchantId,
          creatorId: this.$store.state.user.userId,
          creatorName: this.$store.state.user.userName,
          shopIdList: this.shopIdList,
          materialId: this.materialId,
          batchFlag: 0
        }).then(res => {
          if (res.data.status === 200) {
            this.getMaterialInfo()
            this.modalShow = false
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      } else {
        this.modalShow = false
        this.$Message.error('请至少选择一个门店操作')
      }
    },
    // 上传格式错误
    handleFormatError (file) {
      this.$Notice.warning({
        title: '上传文件格式错误,暂支持zip、apk格式',
        duration: 1.5
      })
    },
    // 上传失败
    handleErr () {
      this.$Message.error('上传失败！')
    },
    // 点击上传成功
    handleSuccess (response, file) {
      let url = file.response.full_url
      let name = file.name
      if (name.indexOf('_') !== -1) {
        if (name.split('_')[0] === 'K802' && name.split('_')[1].split('.')[0].length === 5 && name.split('_')[1].substring(0, 1) === 'V' && (/^[0-9]+$/.test(name.split('_')[1].substring(1, 4)))) {
          saveWholeMaterialInfos({
            'merchantId': this.$store.state.user.merchantId,
            'materialType': 0,
            'materialUrl': url,
            'materialName': name
          }).then(res => {
            if (res.data.status === 200) {
              // 上传成功的回调
              this.$Message.success('上传成功！')
              this.getMaterialInfo()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          }).catch(err => {
            this.$Message.error(`${err}`)
          })
        } else {
          this.$Notice.warning({
            title: '上传文件名称格式错误,应为K802_VYYYY',
            duration: 1.5
          })
        }
      } else {
        this.$Notice.warning({
          title: '上传文件名称格式错误,应为K802_VYYYY',
          duration: 1.5
        })
      }
    },
    changeStore (item) {
      this.storePageIndex = 1
      this.getshopInfo()
    },
    // 切换固件列表与门店列表
    changeBtn (val) {
      this.buttonValue = val
      if (this.buttonValue === '0') {
        this.getMaterialInfo()
      } else if (this.buttonValue === '1') {
        this.getshopInfo()
        this.chooseShopList()
      }
    },
    changePage (index) {
      if (this.buttonValue === '0') {
        this.pageIndex = index
        this.getMaterialInfo()
      } else if (this.buttonValue === '1') {
        this.storePageIndex = index
        this.getshopInfo()
      }
    },
    changePageSize (size) {
      if (this.buttonValue === '0') {
        this.pageSize = size
        this.getMaterialInfo()
      } else if (this.buttonValue === '1') {
        this.storePageSize = size
        this.getshopInfo()
      }
    },
    changeHistoryPage (index) {
      this.historyPageIndex = index
      this.getHistoryInfo()
    },
    changeHistoryPageSize (size) {
      this.historyPageSize = size
      this.getHistoryInfo()
    },
    allSet (row) {
      this.materialId = row.materialId
      getOrgAllTree({ 'merchantId': this.$store.state.user.merchantId, orgType: 1 }).then(res => {
        this.modalShow = true
        if (res.data.status === 200) {
          this.dataTree = [res.data.data]
          this.changeTitle(this.dataTree)
          shopMaterialList({
            'merchantId': this.$store.state.user.merchantId,
            'materialType': 0,
            'materialId': this.materialId,
            'offset': 0,
            'limit': 999
          }).then(res => {
            if (res.data.status === 200) {
              this.checkdList = res.data.data
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 查看详情
    openDraw (row) {
      this.historyShow = true
      this.shopId = row.shopId
      this.getHistoryInfo()
    },
    // 查看历史记录
    getHistoryInfo () {
      this.tableHeight = 0
      getHistoryList({ shopId: this.shopId, materialType: 0, 'limit': String(this.historyPageSize), 'offset': String(this.historyPageSize * (this.historyPageIndex - 1)) }).then(res => {
        if (res.data.status === 200) {
          this.historyList = res.data.data
          this.historyTotal = res.data.totalCount
          if (res.data.data && res.data.data.length >= 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    delPageShow (row) {
      this.delReason = true
      this.materialId = row.materialId
    },
    // 删除物料的某一项
    delMaterial () {
      this.$refs.delValidate.validate((valid) => {
        if (valid) {
          if (this.isDelete) {
            if (!this.isDelete) {
              return
            }
            this.isDelete = false
            delectMaterial({ materialId: this.materialId, remark: this.delValidate.remark }).then(res => {
              this.isDelete = true
              if (res.data.status === 200) {
                this.$Message.success('删除成功！')
                this.delReason = false
                this.isDelete = true
                this.getMaterialInfo()
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            }).catch(err => {
              this.$Message.error(`${err}`)
            })
          }
        }
      })
    },
    cancelDel () {
      this.$refs.delValidate.resetFields()
      this.delReason = false
    },
    // 获取固件列表
    getMaterialInfo () {
      this.loading1 = true
      this.tableHeight = 0
      getMaterialList({ 'merchantId': this.$store.state.user.merchantId, 'materialType': 0, 'limit': String(this.pageSize), 'offset': String(this.pageSize * (this.pageIndex - 1)) }).then(res => {
        this.loading1 = false
        if (res.data.status === 200) {
          this.materialList = res.data.data
          if (res.data.data && res.data.data.length >= 10) {
            this.tableHeight = 520
          }
          if (this.materialList.length > 0) {
            this.materialList.forEach(item => {
              this.$set(item, 'show', false)
            })
          }
          this.total = res.data.totalCount
          if (res.data.data.length / this.pageSize === 0) {
            if (this.pageIndex > 1) {
              this.pageIndex--
              this.getMaterialList()
            }
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取门店物料列表
    getshopInfo () {
      this.loading2 = true
      this.tableHeight = 0
      shopMaterialList({ 'merchantId': this.$store.state.user.merchantId, shopName: this.inputValue, 'materialType': 0, 'limit': String(this.storePageSize), 'offset': String(this.storePageSize * (this.storePageIndex - 1)) }).then(res => {
        this.loading2 = false
        if (res.data.status === 200) {
          this.shopList = res.data.data
          this.storeTotal = res.data.totalCount
          if (res.data.data && res.data.data.length >= 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取门店列表
    chooseShopList () {
      getShopList({ 'merchantId': this.$store.state.user.merchantId, offset: '0', limit: '5000' }).then(res => {
        if (res.data.status === 200) {
          this.storeList = res.data.data
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch((err) => {
        this.$Message.error(`${err}`)
      })
    }
  },
  mounted () {
    if (this.buttonValue === '0') {
      this.getMaterialInfo()
    } else if (this.buttonValue === '1') {
      this.getshopInfo()
      this.chooseShopList()
    }
    if (!this.hasPermission('moms:globalsetting:firmware')) {
      this.$router.replace({ name: 'error_401' })
    }
  }
}
</script>

<style lang='less'>
#firmware-update {
  .table-list {
    border-left: none !important;
    // border-right: none !important;
  }
  .page-bottom {
    // margin-top: 20px;
    padding: 20px;
  }
  .ivu-radio-group-button .ivu-radio-wrapper-checked:first-child {
    color: #fff;
    background: #2d8cf0;
  }
  .ivu-radio-group-button .ivu-radio-wrapper-checked {
    color: #fff;
    background: #2d8cf0;
  }
  .ivu-drawer-body {
    padding: 0;
  }
  .ivu-drawer-header {
    border-bottom: 0;
  }
  .ivu-poptip-body {
    padding: 8px 16px 0 16px;
  }
  .ivu-upload-list-file {
    display: none;
  }
  #modal {
    .modal-content {
      padding: 0 10px;
      .section {
        border: 1px solid #e8eaec;
        width: 230px;
        height: 286px;
        border-radius: 6px;
        overflow: hidden;
        .section-title {
          background: #f9fafc;
          .section-count {
            height: 36px;
            border-bottom: 1px solid #e8eaec;
            padding: 0 24px;
          }
        }
        .section-content {
          padding: 8px 12px;
          height: 248px;
          .content-show {
            width: 100%;
            margin-top: 10px;
            height: 200px;
            overflow: auto;
            .selected-shop {
              li {
                list-style: none;
                margin-top: 11px;
                white-space: nowrap;
              }
            }
          }
        }
      }
    }
  }
}
</style>
